# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：自定义权限校验
"""
from rest_framework.permissions import BasePermission


class MyPermission(BasePermission):
    def has_permission(self, request, view):
        if hasattr(view, "queryset"):
            app_name = view.queryset.model._meta.app_label
            model_name = view.queryset.model._meta.model_name
        else:
            app_name = view.kwargs.get('app_name')
            model_name = view.kwargs.get('model_name')
        user = request.user
        method = request.method
        if not user.is_authenticated:
            return False
            # 如果是超级管理员，直接通过
        if user.is_superuser:
            return True
        if method == "GET":
            perm = f"{app_name}.view_{model_name}"
        elif method == "POST":
            perm = f"{app_name}.add_{model_name}"
        elif method == "DELETE":
            perm = f"{app_name}.delete_{model_name}"
        elif method == 'PUT' or method == 'PATCH':
            perm = f"{app_name}.change_{model_name}"
        else:
            return False

        return user.has_perm(perm)

    def has_object_permission(self, request, view, obj):
        # For object-level permissions, we can refine the logic if needed
        return self.has_permission(request, view)
